package org.zcj.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUtil {

	public static Map<String, Object> upload(HttpServletRequest request) {
		// 设定文件上传的目录
		String fileupload = "upload";
		// 设定返回数据的map,一个是id ,一个是fileUpLoad
		Map<String, Object> map = new HashMap<String, Object>();
		// 创建文件项目工厂对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置文件上传路径
		String upload = request.getSession().getServletContext()
				.getRealPath("/upload/");
		// 获取系统默认的临时文件保存路径，该路径为Tomcat根目录下的temp文件夹
		String temp = System.getProperty("java.io.tmpdir");
		// 设置缓冲区大小为 10M
		factory.setSizeThreshold(1024 * 1024 * 10);
		// 设置临时文件夹为temp
		factory.setRepository(new File(temp));
		// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		// 解析结果放在List中
		try {
			List<FileItem> list = servletFileUpload.parseRequest(request);

			for (FileItem item : list) {
				String name = item.getFieldName();
				InputStream is = item.getInputStream();

				if (name.contains("id")) {
					int id = Integer.parseInt(inputStream2String(is));
					System.out.println(id+"文件内的ID");
					map.put("id", id);
					System.out.println(inputStream2String(is));

				} else if (name.contains("file")) {
					try {
						String fileload = upload + "\\" + item.getName();
						inputStream2File(is, fileload);
						// 存入数据库的路径
						StringBuffer url = request.getRequestURL();
						String tempContextUrl = url
								.delete(url.length()
										- request.getRequestURI().length(),
										url.length())
								.append(request.getServletContext()
										.getContextPath()).append("/")
								.toString();
						map.put("fileload", tempContextUrl + fileupload + "/"
								+ item.getName());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	// 流转化成字符串
	public static String inputStream2String(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString();
	}

	// 流转化成文件
	public static void inputStream2File(InputStream is, String savePath)
			throws Exception {
		System.out.println("文件保存路径为:" + savePath);
		File file = new File(savePath);
		InputStream inputSteam = is;
		BufferedInputStream fis = new BufferedInputStream(inputSteam);
		FileOutputStream fos = new FileOutputStream(file);
		int f;
		while ((f = fis.read()) != -1) {
			fos.write(f);
		}
		fos.flush();
		fos.close();
		fis.close();
		inputSteam.close();

	}

}
